<route lang="json5">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '实验记录',
    enablePullDownRefresh: false,
    navigationStyle: 'custom',
    'app-plus': {
      bounce: 'none',
    },
  },
}
</route>
<template>
  <page-meta :root-font-size="setting.rootFontSize"></page-meta>
  <view>
    <view style="position: sticky; top: 0; z-index: 99; width: 100%" class="task-custom">
      <wd-navbar :title="form.projectName || '实验记录'" :bordered="false" safeAreaInsetTop>
        <template #left>
          <wd-icon name="thin-arrow-left" size="22px" color="white" @click="goBack"></wd-icon>
        </template>
      </wd-navbar>
    </view>
    <view
      :style="{
        padding: '4px 0',
        position: 'sticky',
        backgroundColor: '#fff',
        top: 0,
        zIndex: '100',
      }"
    >
      <ActionBar
        permissionPrefix="experiment_experimentRecord"
        :data="form"
        @click="onAction"
        :loading="submiting"
        :disabledList="[
          'agreed',
          'submit',
          'add',
          'revoke',
          'edit',
          'revive',
          'del',
          'close',
          'open',
        ]"
        :afterBtns="[
          {
            list: [
              {
                name: '提交',
                command: 'submit',
                authType: 'apply_new',
                enabled: () => {
                  return form.id && [0, 3].includes(form.status) && form.taskAllStatus == 1;
                },
              },
              ,
              {
                name: '审核',
                command: 'agreed',
                authType: 'apply_complete',
                enabled: () => {
                  if (form.id && form.instanceId && form.taskAllStatus == 1) {
                    return form.reviewByMe;
                  }
                  return form.id && form.status === 1 && form.taskAllStatus == 1;
                },
              },

              {
                name: '撤回',
                command: 'revoke',
                authType: 'apply_cancel',
                enabled: () => {
                  return form.id && form.status === 1 && form.taskAllStatus == 1;
                },
              },
              {
                name: '弃审',
                command: 'revive',
                authType: 'apply_abandon',
                enabled: () => {
                  return form.id && form.status === 2 && form.taskAllStatus == 1;
                },
              },
              // {
              //     name: $t('查看实验报告'),
              //     command: 'report',
              //     enabled: () => {
              //         return state.form.id && state.form.status === 2 && state.form.taskAllStatus == 1;
              //     },
              // },
            ],
          },
        ]"
      ></ActionBar>
    </view>
    <view class="scroll-container">
      <view class="left-container" :class="{ hide: !showCatalogues }" :style="{}">
        <view class="toggle" @click="toggleCatalogues">
          <text class="cuIcon-back"></text>
          <text>收起</text>
        </view>
        <scroll-view
          scrollY
          class="left"
          :style="{
            height: hideTitleNav ? heightStyle : `calc(100vh - 80rpx - ${statusBar}px)`,
          }"
          :scroll-with-animation="true"
        >
          <view
            class="item"
            :id="'reportView' + item.value"
            :class="{ active: currentNode === item.value }"
            v-for="(item, index) in catalogues"
            :key="index"
          >
            <view
              class="item_text"
              :class="{ no_data: item.noData }"
              @click="onClickTab(item, index)"
            >
              {{ item.name }}
            </view>
          </view>
        </scroll-view>
      </view>

      <scroll-view
        class="flex-1 scroll-view"
        :style="{ height: heightStyle }"
        :scroll-with-animation="true"
        :scrollY="!scrollYDisabled"
        @scroll="onViewScroll"
        :scroll-into-view="'reportView' + nodeNum"
      >
        <view
          class="open"
          :class="{ show: showOpenMenu }"
          :style="{ top: 130 + 'px' }"
          @click.stop="toggleCatalogues"
          @touchstart="onTouchOpenMenu"
        >
          <text class="cuIcon-right"></text>
        </view>

        <th-card id="reportView1" title="任务信息">
          <th-form labelWidth="100px">
            <th-form-item label="项目名称" v-if="schemeDetail.petitionName">
              <text class="text">{{ schemeDetail.petitionName }}</text>
            </th-form-item>
            <th-form-item label="任务编码">
              <text class="text">{{ schemeDetail.projectCode }}</text>
            </th-form-item>
            <th-form-item label="需求产品名称" v-if="schemeDetail.compoundFlag == 1">
              <wd-textarea
                disabled
                type="textarea"
                auto-height
                v-model="schemeDetail.rdDemandEntityInvName"
                clearable
                style="width: 100%"
                no-border
                class="diabledStyle"
                placeholder=" "
              ></wd-textarea>
            </th-form-item>
            <th-form-item label="产品名称" v-else>
              <wd-textarea
                disabled
                type="textarea"
                auto-height
                v-model="schemeDetail.invName"
                clearable
                style="width: 100%"
                no-border
                class="diabledStyle"
                placeholder=" "
              ></wd-textarea>
            </th-form-item>
            <th-form-item label="需求产品规格" v-if="schemeDetail.compoundFlag == 1">
              <wd-textarea
                disabled
                type="textarea"
                auto-height
                v-model="schemeDetail.rdDemandEntityInvStd"
                clearable
                style="width: 100%"
                no-border
                class="diabledStyle"
                placeholder=" "
              ></wd-textarea>
            </th-form-item>
            <th-form-item label="产品规格" v-else>
              <wd-textarea
                disabled
                type="textarea"
                auto-height
                v-model="schemeDetail.invStd"
                clearable
                style="width: 100%"
                no-border
                class="diabledStyle"
                placeholder=" "
              ></wd-textarea>
            </th-form-item>
            <th-form-item label="任务负责人">
              <view>
                <text
                  class="text"
                  v-for="(item, index) in schemeDetail.projectHeadName"
                  :key="index"
                >
                  {{ index > 0 ? '，' : '' }}{{ item.userName }}
                </text>
              </view>
              <!-- <text class="text">{{ schemeDetail.projectHeadName }}</text> -->
            </th-form-item>
            <!-- <th-form-item label="技术负责人">
							<text class="text">{{ schemeDetail.technologyHeadName }}</text>
						</th-form-item> -->
            <th-form-item label="任务成员">
              <view>
                <text
                  class="text"
                  v-for="(item, index) in schemeDetail.rdProjectUserEntity"
                  :key="index"
                >
                  {{ index > 0 ? '，' : '' }}{{ item.userName }}
                </text>
              </view>
            </th-form-item>
            <th-form-item label="需求描述">
              <wd-textarea
                disabled
                type="textarea"
                auto-height
                v-model="schemeDetail.description"
                clearable
                style="width: 100%"
                no-border
                class="diabledStyle"
                placeholder=" "
              ></wd-textarea>
              <!-- <text class="text">{{ schemeDetail.description }}</text> -->
            </th-form-item>
            <th-form-item label="反应方程式">
              <text class="text">
                <image
                  class="craft-row-img"
                  :src="schemeDetail.equation"
                  mode="scaleToFill"
                  @click="previewFileHandle(schemeDetail.equation)"
                />
              </text>
            </th-form-item>
          </th-form>
        </th-card>
        <th-card id="reportView2" title="记录信息">
          <th-form labelWidth="100px">
            <th-form-item label="单据编号" v-if="form.id">
              <text class="text">{{ form.recordNo }}</text>
            </th-form-item>
            <th-form-item label="实验日期" v-if="form.id">
              <text class="text">{{ form.createTime }}</text>
            </th-form-item>
            <th-form-item label="实验次数" v-if="form.id">
              <text class="text">{{ form.sn }}</text>
            </th-form-item>
            <th-form-item label="记录描述">
              <wd-textarea
                :disabled="[1, 2].includes(form.status)"
                type="textarea"
                auto-height
                v-model="form.description"
                placeholder=" "
                clearable
                style="width: 100%"
                no-border
                class="diabledStyle"
              ></wd-textarea>
              <!-- <text class="text" v-else>{{ form.description }}</text> -->
            </th-form-item>
            <th-form-item label="产品名称" v-if="schemeDetail.compoundFlag == 1">
              <wd-textarea
                disabled
                type="textarea"
                auto-height
                v-model="schemeDetail.invName"
                clearable
                style="width: 100%"
                no-border
                class="diabledStyle"
                placeholder="产品名称"
              ></wd-textarea>
            </th-form-item>
            <th-form-item label="产品规格" v-if="schemeDetail.compoundFlag == 1">
              <wd-textarea
                disabled
                type="textarea"
                auto-height
                v-model="schemeDetail.invStd"
                clearable
                style="width: 100%"
                no-border
                class="diabledStyle"
                placeholder="产品规格"
              ></wd-textarea>
            </th-form-item>
            <th-form-item label="实验目的">
              <wd-textarea
                disabled
                type="textarea"
                auto-height
                v-model="schemeDetail.purpose"
                placeholder=" "
                clearable
                style="width: 100%"
                no-border
                class="diabledStyle"
              ></wd-textarea>
              <!-- <text class="text" v-else>{{ form.purpose }}</text> -->
            </th-form-item>
          </th-form>
          <view>
            <view class="viewLabel"><text>反应装置</text></view>
            <view class="table-container">
              <table class="analysis-table">
                <tbody>
                  <tr>
                    <th>反应装置</th>
                    <th>用料规格</th>
                    <th>最大搅拌量</th>
                    <th>最小搅拌量</th>
                    <th>单位</th>
                  </tr>
                  <tr align="center" v-for="(item, index) in form.deviceList" :key="index">
                    <td>{{ item.name }}</td>
                    <td>{{ item.capacity }}</td>
                    <td>{{ item.maxValue }}</td>
                    <td>{{ item.minValue }}</td>
                    <td>{{ item.unit }}</td>
                  </tr>
                </tbody>
              </table>
            </view>
          </view>
          <!-- <th-form labelWidth="100px">
						<th-form-item label="反应装置" class="viewTable">
							<view class="table-container">
								<table class="analysis-table">
									<tbody>
										<tr>
											<th>反应装置</th>
											<th>用料规格</th>
											<th>最大搅拌量</th>
											<th>最小搅拌量</th>
											<th>单位</th>
										</tr>
										<tr align="center" v-for="(  item, index  ) in form.deviceList" :key="index">
											<td>{{ item.name }}</td>
											<td>{{ item.capacity }}</td>
											<td>{{ item.maxValue }}</td>
											<td>{{ item.minValue }}</td>
											<td>{{ item.unit }}</td>
										</tr>
									</tbody>
								</table>
							</view>
						</th-form-item>
					</th-form> -->
        </th-card>
        <th-card id="reportView3" title="用料及配比">
          <view class="table-container">
            <table class="analysis-table">
              <tbody>
                <tr>
                  <th style="width: 320rpx; min-width: 9.5rem">用料名称</th>
                  <th style="width: 280rpx; min-width: 380rpx">用料规格</th>
                  <th style="width: 280rpx; min-width: 180rpx">密度</th>
                  <th style="width: 280rpx; min-width: 180rpx">占比（%）</th>
                  <th
                    style="width: 280rpx; min-width: 480rpx"
                    v-if="schemeDetail.compoundFlag != 1"
                  >
                    范围
                  </th>
                  <th style="width: 280rpx; min-width: 280rpx">计划用量</th>
                  <th
                    style="width: 280rpx; min-width: 280rpx"
                    v-if="schemeDetail.compoundFlag != 1"
                  >
                    实际用量
                  </th>
                  <th style="width: 320rpx; min-width: 180rpx">单位</th>
                </tr>
                <tr
                  align="center"
                  v-for="(item, index) in materialList"
                  :key="index"
                  v-if="materialList.length"
                >
                  <td>{{ item.invName }}</td>
                  <td>{{ item.invStd }}</td>
                  <td>{{ item.density }}</td>
                  <td>{{ item.proportion }}</td>
                  <td v-if="schemeDetail.compoundFlag != 1">
                    <text>
                      {{
                        minPlanDosage(
                          item.density,
                          item.proportion,
                          form.deviceList && form.deviceList[0].minValue,
                        )
                      }}
                    </text>
                    ~
                    <text>
                      {{
                        maxPlanDosage(
                          item.density,
                          item.proportion,
                          form.deviceList && form.deviceList[0].maxValue,
                        )
                      }}
                    </text>
                  </td>
                  <td>{{ item.planDosage }}</td>
                  <td v-if="schemeDetail.compoundFlag != 1">{{ item.dosage }}</td>
                  <td>{{ item.unit }}</td>
                </tr>

                <tr align="center" v-if="schemeDetail.compoundFlag == 1">
                  <td>合计</td>
                  <td></td>
                  <td></td>
                  <td>{{ totalProportion(materialList) }}</td>
                  <td></td>
                  <td></td>
                </tr>
              </tbody>
            </table>
          </view>
          <!-- <thTable :data="materialList" :options="materialTableOptions"></thTable> -->
        </th-card>
        <th-card id="reportView4" title="用料产出">
          <view class="table-container" v-if="form.status">
            <table class="analysis-table">
              <tbody>
                <tr>
                  <th>用料名称</th>
                  <th>用料规格</th>
                  <th>数量</th>
                  <th>单位</th>
                </tr>
                <tr align="center" v-for="(item, index) in recordOutList" :key="index">
                  <td>{{ item.invName }}</td>
                  <td>{{ item.invStd }}</td>
                  <td>{{ item.dosage }}</td>
                  <td>{{ item.unit }}</td>
                </tr>
              </tbody>
            </table>
          </view>
          <view v-else>
            <wd-button :round="false" style="margin-bottom: 20rpx" @click="addRecordOutList">
              插行
            </wd-button>
            <view class="table-container">
              <table class="analysis-table">
                <tbody>
                  <tr>
                    <th style="width: 320rpx; min-width: 9.5rem">
                      <text class="cell--required-icon"></text>
                      用料名称
                    </th>
                    <th style="width: 280rpx; min-width: 280rpx">用料规格</th>
                    <th style="width: 280rpx; min-width: 280rpx">
                      <text class="cell--required-icon"></text>
                      数量
                    </th>
                    <th style="width: 280rpx; min-width: 280rpx">
                      <text class="cell--required-icon"></text>
                      单位
                    </th>
                    <th style="width: 280rpx; min-width: 280rpx">操作</th>
                  </tr>
                  <tr align="center" v-for="(item, index) in recordOutList" :key="index">
                    <td>
                      <wd-input
                        v-model="item.invName"
                        clearable
                        no-border
                        style="background-color: transparent"
                      />
                    </td>
                    <td>
                      <wd-input
                        v-model="item.invStd"
                        clearable
                        no-border
                        style="background-color: transparent"
                      />
                    </td>
                    <td>
                      <wd-input
                        v-model="item.dosage"
                        clearable
                        type="number"
                        no-border
                        style="background-color: transparent"
                      />
                    </td>
                    <td>
                      <wd-select-picker
                        type="radio"
                        :show-confirm="false"
                        v-model="item.unit"
                        :columns="unitList"
                        style="background-color: transparent"
                      />
                    </td>
                    <td>
                      <wd-button type="text" @click="addRecordOutList">插行</wd-button>
                      <wd-button
                        type="text"
                        @click="rowDel(index)"
                        style="margin-left: 10rpx; color: #fa4350"
                      >
                        删行
                      </wd-button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </view>
          </view>
        </th-card>
        <view class="tabs-wrap">
          <view class="header">
            <view class="tabs">
              <view class="tab" :class="tabIndex === 0 ? 'on' : ''" @click="changeTab(0)">
                <text>工艺流程</text>
              </view>
              <view class="tab" :class="tabIndex === 1 ? 'on' : ''" @click="changeTab(1)">
                <text>实验过程记录</text>
              </view>
            </view>
            <view v-if="tabIndex">
              <wd-button
                type="icon"
                size="18px"
                icon="save"
                @click="saveHandle"
                v-if="![1, 2].includes(form.status)"
              ></wd-button>
            </view>
          </view>
          <view style="min-height: 100px; margin-top: 12px">
            <template v-if="tabIndex === 0">
              <ExperimnetStepPreview
                :materialList="processList"
                mode="record"
                @switchChange="changeTab(1)"
                v-if="[1, 2].includes(form.status)"
              />

              <fpExperimnetStep
                :materialList="materialStepList"
                v-model="processList"
                @remove="onRemoveProcess"
                mode="record"
                v-else-if="[null, 0, 3].includes(form.status) && schemeDetail.compoundFlag == 1"
                @createRecord="handleSaveRecord"
                v-model:modelDisabled="scrollYDisabled"
              ></fpExperimnetStep>

              <ExperimentStep
                v-else
                :materialList="materialStepList"
                v-model="processList"
                @remove="onRemoveProcess"
                @createRecord="handleSaveRecord"
                v-model:modelDisabled="scrollYDisabled"
                @switchChange="changeTab(1)"
                mode="record"
              ></ExperimentStep>
            </template>
            <template v-if="tabIndex === 1">
              <ExperimnetStepTablePreview
                :record-id="form.id"
                :materialList="tableStepList"
                v-if="[1, 2].includes(form.status) || form.taskAllStatus != 1"
              />
              <demo
                v-else
                :record-id="form.id"
                :stepList="processList"
                ref="recordExp"
                :materialList="materialStepList"
              ></demo>
            </template>
          </view>
        </view>
        <!-- <th-card id="reportView5" title="工艺流程及参数记录">
					<ExperimnetStepPreview :materialList="processList" mode="record" v-if="[1, 2].includes(form.status)" />

					<fpExperimnetStep :materialList="materialStepList" v-model="processList" @remove="onRemoveProcess"
						mode="record" v-else-if="[null, 0, 3].includes(form.status) && schemeDetail.compoundFlag == 1"
						@createRecord="handleSaveRecord" v-model:modelDisabled="scrollYDisabled">
					</fpExperimnetStep>

					<ExperimentStep v-else :materialList="materialStepList" v-model="processList" @remove="onRemoveProcess"
						@createRecord="handleSaveRecord" v-model:modelDisabled="scrollYDisabled" mode="record">
					</ExperimentStep>

				</th-card> -->
        <th-card id="reportView6" title="附件" v-if="schemeDetail.compoundFlag == 1">
          <view class="table-container">
            <table class="analysis-table">
              <tbody>
                <tr>
                  <th>附件名称</th>
                  <th
                    v-if="[null, 0, 3].includes(form.status) && form.taskAllStatus == 1"
                    style="width: 280rpx; min-width: 380rpx"
                  >
                    操作
                  </th>
                </tr>
                <tr
                  align="center"
                  v-for="(item, index) in fileList"
                  :key="index"
                  @click="previewFile(item.fileUrl)"
                >
                  <td>
                    <wd-input
                      v-if="[null, 0, 3].includes(form.status) && form.taskAllStatus == 1"
                      v-model="item.fileName"
                      clearable
                      no-border
                      style="background-color: transparent"
                    />
                    <text v-else>{{ item.fileName }}</text>
                  </td>
                  <td
                    v-if="[null, 0, 3].includes(form.status) && form.taskAllStatus == 1"
                    style="width: 280rpx; min-width: 280rpx"
                  >
                    <uploadFile @complete="uploadComplete"></uploadFile>
                    <button
                      type="primary"
                      size="mini"
                      @click="previewFileView(item.fileUrl)"
                      style="margin-left: 10rpx"
                    >
                      预览
                    </button>
                  </td>
                </tr>
              </tbody>
            </table>
          </view>
        </th-card>
        <th-card id="reportView7" title="审核信息" v-if="[1, 2, 3].includes(form.status)">
          <view class="row-list">
            <view>
              <flowTable ref="flowDetailsTableRef" :processInstanceId="form.instanceId"></flowTable>
            </view>
          </view>
        </th-card>
      </scroll-view>
    </view>
    <wd-popup
      v-model="revokeShow"
      position="center"
      custom-class="wdPopupStyle"
      @close="
        revokeShow = false;
        comment = '';
      "
    >
      <view style="display: flex; flex-direction: column; height: 100%">
        <view class="title">撤回原因</view>
        <view class="content-body">
          <wd-textarea
            v-model="comment"
            placeholder="请填写撤回原因"
            auto-height
            :maxlength="2000"
            no-border
            prop="revokeComment"
            class="reovke-textarea"
          />
        </view>

        <view class="flow-btn-fixed">
          <view class="btn_group" style="width: 100%">
            <view
              class="btn"
              @click="
                revokeShow = false;
                comment = '';
              "
            >
              取消
            </view>
            <view class="btn primary" @click="handleRevoke">撤回</view>
          </view>
        </view>
      </view>
    </wd-popup>
    <wd-popup
      v-model="completeShow"
      position="center"
      custom-class="wdPopupStyle"
      @close="
        completeShow = false;
        completeComment = '';
      "
    >
      <view style="display: flex; flex-direction: column; height: 100%">
        <view class="title">审核</view>
        <view class="content-body">
          <wd-textarea
            v-model="completeComment"
            placeholder="请填写审核意见"
            auto-height
            :maxlength="2000"
            no-border
            prop="revokeComment"
            class="reovke-textarea"
          />
        </view>

        <view class="flow-btn-fixed">
          <view class="btn_group" style="width: 100%">
            <view class="btn danger" @click="oncomplete(1)">拒绝</view>
            <view class="btn primary" @click="oncomplete(0)">同意</view>
          </view>
        </view>
      </view>
    </wd-popup>
    <wd-popup
      v-model="reviveShow"
      position="center"
      custom-class="wdPopupStyle"
      @close="
        reviveShow = false;
        reviveComment = '';
      "
    >
      <view style="display: flex; flex-direction: column; height: 100%">
        <view class="title">弃审原因</view>
        <view class="content-body">
          <wd-textarea
            v-model="reviveComment"
            placeholder="请填弃审原因"
            auto-height
            :maxlength="2000"
            no-border
            prop="revokeComment"
            class="reovke-textarea"
          />
        </view>

        <view class="flow-btn-fixed">
          <view class="btn_group" style="width: 100%">
            <view
              class="btn"
              @click="
                revokeShow = false;
                reviveComment = '';
              "
            >
              取消
            </view>
            <view class="btn primary" @click="handleRevive">弃审</view>
          </view>
        </view>
      </view>
    </wd-popup>
  </view>
</template>
<script lang="ts" setup>
import { useSetting } from '@/stores/setting';
import {
  addObj,
  putObj,
  getObj,
  submitProcess,
  revokeProcess,
  getPageByTask,
  complete,
  abandon,
} from '@/service/pm-record';

import { request } from '@/utils/request';
import ActionBar from '../components/actionBar';
import { getRdTaskDetail } from '@/service/pm-report';
import { getObj as querySchemeDetail } from '@/service/pm-experiment';
import ExperimnetStepPreview from '../components/ExperimnetStepPreview.vue';
import ExperimentStep from '../components/ExperimnetStep.vue';
import fpExperimnetStep from '../components/fpExperimnetStep.vue';
import { useMessage, useToast } from 'wot-design-uni';
import { useDict } from '../hooks/dict';
import dayjs from 'dayjs';
import { totalProportion } from '../utils/index';
import showModal from '@/utils/modal';
// import { formatByDayjs } from '@/utils/util';
import demo from './component/demo/index.vue';
import ExperimnetStepTablePreview from '../../report/components/ExperimnetStepTablePreview.vue';

const { pm_need_unit: unitList } = useDict('pm_need_unit');
const setting = useSetting();
const message = useMessage();
const toast = useToast();
const statusBar = ref(130);
const hideTitleNav = ref(false);
const showCatalogues = ref(false);
const currentNode = ref(1);
const nodeNum = ref(1);
const showOpenMenu = ref(true);
const preScrollTop = ref(0);
const openMenuBottom = ref(300);
const openMenuTouch = ref({
  startY: 0,
  bottom: 0,
});

const scrollYDisabled = ref(false);

const heightStyle = computed(() => {
  return `calc(100vh - ${statusBar.value}px)`;
});

const tabIndex = ref(0);

const catalogues = ref([
  {
    name: '任务信息',
    value: 1,
  },
  {
    name: ' 记录信息 ',
    value: 2,
  },
  {
    name: '用料及配比',
    value: 3,
  },
  {
    name: '用料产出',
    value: 4,
  },
  {
    name: '工艺流程及参数',
    value: 5,
  },
  {
    name: '附件',
    value: 6,
  },
  {
    name: '审核信息',
    value: 7,
  },
]);

const tab = reactive({
  name: 1,
});

const tabList = ref([
  {
    name: '工艺流程',
    value: 1,
  },
  {
    name: '实验过程记录',
    value: 2,
  },
]);

const schemeDetail: any = ref({
  projectName: '',
  projectCode: '',
  invName: '',
  invCode: '',
  projectHeadName: '',
});

// 提交表单数据
const form: any = reactive({
  id: '',
  status: null,
});

const processList = ref([]);

const materialList = ref([]);
const recordOutList = ref([]);

const materialStepList = computed(() => {
  return materialList.value
    .filter((item) => item.invName)
    .map((item) => {
      const res = {
        invCode: item.invCode,
        invName: item.invName,
        invStd: item.invStd,
        dosage: item.dosage || '',
        unit: item.unit,
      };
      if (item.id) {
        res.id = item.id;
      }
      if (item.schemeId) {
        res.schemeId = item.schemeId;
      }
      return res;
    });
});

const _source = ref('');
const firstView = ref(false);

onLoad((options) => {
  form.id = options.id;
  form.schemeId = options.schemeId;
  _source.value = options?._source || '';

  if (form.id) {
    init({
      id: form.id,
    });
  } else {
    getSchemeDetail(form.schemeId);
    firstView.value = true;
  }
});

onShow(() => {
  console.log(form.id);
  if (form.id) {
    getProcessPageByTask(form.id);
  }
});

const goBack = () => {
  uni.navigateBack();
};

const fileList = ref([
  {
    fileName: '',
    fileUrl: '',
  },
]);

const unifyNumber = (num) => {
  if (num === '') return '';

  let handleNum = parseFloat(num);
  let isToFixed =
    handleNum.toString().includes('.') && handleNum.toString().split('.')[1].length > 6;
  if (isToFixed) {
    return handleNum.toFixed(6);
  } else {
    return handleNum;
  }
};

const isNotNum = (val: string | null | number): boolean => {
  if (typeof val === 'string' && !isNaN(Number(val))) {
    return val.indexOf('.') < 0 && val.indexOf('0') == 0;
  } else {
    return isNaN(Number(val));
  }
};

const transferAndToFixed = (num, length = 0) => {
  const str = num.toFixed(length).toString();
  const reg = str.indexOf('.') > -1 ? /(\d)(?=(\d{3})+\.)/g : /(\d)(?=(\d{3})+$)/g;
  return str.replace(reg, '$1,');
};

const maxPlanDosage = (density: number, proportion: number, maxValue: number) => {
  if (isNotNum(density)) return 0;
  if (isNotNum(maxValue)) return 0;
  if (isNotNum(proportion)) return 0;

  let maxNum = 0;
  //密度（g/ml） * 占比 * 最大搅拌量（ml）
  maxNum = Number(density) * Number(proportion) * Number(maxValue);
  return unifyNumber(transferAndToFixed(maxNum / 100, 4));
};

const minPlanDosage = (density: number, proportion: number, minValue: number) => {
  if (isNotNum(density)) return 0;
  if (isNotNum(minValue)) return 0;
  if (isNotNum(proportion)) return 0;
  let minNum = 0;
  //密度（g/ml） *  占比 * 最小搅拌量（ml）
  minNum =
    transferAndToFixed(Number(density), 4) *
    transferAndToFixed(Number(proportion), 4) *
    transferAndToFixed(Number(minValue), 4);
  return unifyNumber(transferAndToFixed(minNum / 100, 4));
};

const tabClick = (val, index) => {
  if (typeof val != 'number') return;
  tab.name = val;
  console.log(tab.name);
};

const onClickTab = (e) => {
  // this.childrenNode = ""
  if (nodeNum.value === e.value && nodeNum.value !== currentNode.value) {
    nodeNum.value = null;
    nextTick(() => {
      nodeNum.value = e.value;
    });
  } else {
    nodeNum.value = e.value;
  }
  currentNode.value = e.value;
  setTimeout(() => {
    currentNode.value = e.value;
    setTabs();
  }, 300);
};

const setTabs = () => {
  const query = uni.createSelectorQuery().in(this);
  catalogues.value.forEach((item: any) => {
    query
      .select(`#reportView${item.value}`)
      .boundingClientRect((data) => {
        item.nodeHeight = data.height + 10;
      })
      .exec();
  });
};

const uploadComplete = (ref) => {
  const { fileName, url } = ref;
  console.log(ref);
  fileList.value = [
    {
      fileName: fileName,
      fileUrl: url,
    },
  ];
};

const toggleCatalogues = () => {
  showCatalogues.value = !showCatalogues.value;
  if (!showCatalogues.value) {
    setTimeout(() => {
      showOpenMenu.value = true;
    }, 260);
  } else {
    showOpenMenu.value = false;
  }
  setTimeout(() => {
    setTabs();
  }, 1000);
};
const onSchemeInited = (e) => {
  setTabs();
};
const onNotesInited = (e) => {
  setTabs();
};

const isImage = (url: string) => {
  if (!url) return '';
  const suffix = url.replace(/.*\./, '') || url;
  return ['jpg', 'jpeg', 'png', 'gif', 'svg', 'JPG', 'JPEG', 'PNG', 'GIF', 'SVG', 'WebP'].includes(
    suffix,
  );
};

const previewFile = (url) => {
  if ([null, 0, 3].includes(form.status) && form.taskAllStatus == 1) return;
  if (!url) return;
  if (isImage(url)) {
    preview(url);
  } else {
    previewFileHandle(url);
  }
};

const previewFileView = (url) => {
  if (!url) return;
  if (isImage(url)) {
    preview(url);
  } else {
    previewFileHandle(url);
  }
};

const previewFileHandle = (file) => {
  uni.navigateTo({
    url: '/pages/pm/preview-online?url=' + file,
  });
};
const onViewScroll = (e) => {
  if (e.detail.scrollTop <= 0) {
    hideTitleNav.value = false;
  } else {
    hideTitleNav.value = true;
  }
  // if (preScrollTop.value && e.detail.scrollTop > 0) {
  // 	if (e.detail.scrollTop - preScrollTop.value < 0) {
  // 		preScrollTop.value = e.detail.scrollTop
  // 	} else if (e.detail.scrollTop - preScrollTop.value > 0) {
  // 		preScrollTop.value = e.detail.scrollTop
  // 	}

  // } else {
  // 	preScrollTop.value = e.detail.scrollTop
  // }
  if (e.detail.scrollTop <= catalogues.value[0].nodeHeight - 12) {
    currentNode.value = 1;
    return;
  }
  let aboveHeight = 0;
  for (let i = 0; i < catalogues.value.length; i++) {
    const _curr = catalogues.value[i];
    aboveHeight += _curr.nodeHeight;
    if (
      e.detail.scrollTop >= aboveHeight &&
      e.detail.scrollTop <= aboveHeight + (catalogues.value[i + 1]?.nodeHeight || 0) - 12
    ) {
      currentNode.value = _curr.value + 1;
      // catalogues.value.map(item => item.openChildren = false)
      // // 判断当前类型有子节点且没有展开则自动展开
      // const currentNode = catalogues.value[i + 1]
      // if (currentNode && currentNode.children && currentNode.children.length && !currentNode.openChildren) {
      //     currentNode.openChildren = true
      // }
      break;
    }
  }
};

/**
 * 实验记录查看
 */
const tableStepList = ref([]);
const getStepTable = async (record) => {
  if (!record) return;
  try {
    const { data } = await request({
      url: `/pm/experimentRecord/stepTable/${record}`,
      method: 'get',
    });

    tableStepList.value = data;
  } catch (error) {
    console.log(error);
    // options.onError(error as any);
  }
};

const onTouchOpenMenu = (e) => {
  openMenuTouch.value.startY = e.touches[0].clientY;
  openMenuTouch.value.bottom = openMenuBottom.value;
};
const flowDetailsTableRef = ref();

const init = (params) => {
  uni.showLoading();
  getObj(params.id)
    .then((res) => {
      console.log(res.data);
      if (!res.data) return;
      Object.assign(form, res.data);
      fileList.value = [
        {
          fileName: res.data.attachmentName || '',
          fileUrl: res.data.attachment || '',
        },
      ];

      if (res.data.schemeId) {
        getSchemeDetail(res.data.schemeId);
      }

      if (res.data.dosageList) {
        materialList.value = res.data.dosageList.filter((item) => !item.type);
        recordOutList.value = res.data.dosageList.filter((item) => item.type) || [
          { type: 1, unit: 'g' },
        ];
      }
      if (res.data.stepList) {
        processList.value = res.data.stepList.map((item) => {
          item.recallFlag = res.data.recallFlag;
          item.dosageList &&
            item.dosageList.forEach((d) => {
              d.recallFlag = res.data.recallFlag;
            });
          item.paramList &&
            item.paramList.forEach((p) => {
              p.recallFlag = res.data.recallFlag;
            });
          if (item.processName === '中控') {
            item.sampletimeList = [];
            item.checkList = [];
            item.paramList.map((v) => {
              if (v.mcFlag == 1) {
                item.sampletimeList.push(v);
              } else {
                item.checkList.push({
                  analysisId: v.analysisId,
                  analysisName: v.analysisName,
                  itemName: v.paramName,
                  recallFlag: v.recallFlag,
                  status: v.status,
                });
              }
            });
          }

          item.inspectionList = [];
          item.isVerify = item.qcFlag;
          return item;
        });
      }
      // 切换回调
      if (canSwitch.value) {
        tabIndex.value = 1;
        canSwitch.value = false;
      }
      console.log(processList.value);
      getProcessPageByTask(res.data.id);

      // getStepTable(res.data.id);

      nextTick(() => {
        flowDetailsTableRef.value?.getFlowDetails();
      });
    })
    .finally(() => {
      uni.stopPullDownRefresh();
      uni.hideLoading();
    });
};

/**
 * 更新工艺流程参数
 */
uni.$on('updateStep', (id) => {
  updateStep(id);
});
const updateStep = (id) => {
  if (!id) return console.log('没有记录id');
  getObj(id).then((res) => {
    if (res.data.stepList) {
      processList.value = res.data.stepList.map((item) => {
        item.recallFlag = res.data.recallFlag;
        item.dosageList &&
          item.dosageList.forEach((d) => {
            d.recallFlag = res.data.recallFlag;
          });
        item.paramList &&
          item.paramList.forEach((p) => {
            p.recallFlag = res.data.recallFlag;
          });
        if (item.processName === '中控') {
          item.sampletimeList = [];
          item.checkList = [];
          item.paramList.map((v) => {
            if (v.mcFlag == 1) {
              item.sampletimeList.push(v);
            } else {
              item.checkList.push({
                analysisId: v.analysisId,
                analysisName: v.analysisName,
                itemName: v.paramName,
                recallFlag: res.data.recallFlag,
                status: v.status,
              });
            }
          });
        }
        item.inspectionList = [];
        item.isVerify = item.qcFlag;
        return item;
      });
      getProcessPageByTask(res.data.id);
    }
  });
};

const getProcessPageByTask = function (id: string) {
  getPageByTask({ pid: id, size: 999 })
    .then((res) => {
      if (res.code === 0) {
        console.log(res.data);
        if (form.stepList) {
          processList.value.forEach((item: any) => {
            if (item.putIntoFlag && !item.dosageList?.length) {
              item.dosageList = [{ invName: null, unit: null }];
            }
            item.undraggable = true;

            if (item.processName === '终检') {
              ZJReportStatusList.value = res.data.records.filter((item) => item.type === 1);
              // if (zj) {
              // 	 = zj.status
              // }
            }

            const list = res.data.records.filter((v) => v.pid === item.id) || [];
            if (!item.inspectionList) {
              item.inspectionList = [];
            }
            if (item.isVerify) {
              const t = JSON.parse(JSON.stringify(item));
              delete t.inspectionList;
              item.inspectionList = [];
              item.inspectionList.push({
                ...t,
                id: '',
                show: false,
              });
            }

            if (list && list.length) {
              item.inspectionList = list.map((row) => {
                row.show = false;
                return row;
              });
              return;
            }
          });
          // processList.value = form.stepList;
        }
      }
    })
    .catch((err) => {
      console.log(err);
      toast.error(err.msg || err.message || '获取工序报检信息失败');
    });
};

const addRecordOutList = () => {
  recordOutList.value.push({
    invName: '',
    invStd: '',
    dosage: null,
    unit: '',
    type: 1,
  });
};
const rowDel = (rowIndex) => {
  recordOutList.value.splice(rowIndex, 1);
};

const preview = (url) => {
  if (!url) return;
  uni.previewImage({
    urls: [url],
  });
};

const previewWeb = (url) => {
  uni.navigateTo({
    url: '/pages/pm/preview-online?url=' + url + '&isWeb=1',
  });
};

const getSchemeDetail = function (schemeId: string) {
  querySchemeDetail({ id: schemeId })
    .then((res) => {
      if (res.code === 0) {
        schemeDetail.value = res.data;
        schemeDetail.value.projectCode = res.data.itemCode;
        schemeDetail.value.projectName = res.data.itemName;
        if (!form.equation) {
          form.equation = res.data.equation;
        }
        form.deviceList = res.data.equipmentList;

        if (res.data.taskCode && res.data.demandCode) {
          getProjectInfo({
            id: res.data.taskId,
            taskCode: res.data.taskCode,
            demandCode: res.data.demandCode,
          });
        }
        if (!form.id) {
          form.schemeId = res.data.id;
          materialList.value = res.data.dosageList.map((item) => {
            item.planDosage = item.dosage;
            item.dosage = null;
            delete item.id;
            return item;
          });
          if (!res.data.processList) {
            res.data.processList = [];
          }
          res.data.processList.map((item) => {
            if (item.putIntoFlag && !item.dosageList?.length) {
              item.dosageList = [{ invName: null, unit: null }];
            }
            if (item.dosageList?.length) {
              item.dosageList.forEach((dosage) => {
                delete dosage.id;
              });
            }
            if (item.paramList?.length) {
              item.paramList.forEach((param) => {
                delete param.id;
                param.schemeParamValue = param.paramValue;
                param.paramValue = null;
              });
            }
            item.inspectionList = [];
            if (item.isVerify) {
              const t = JSON.parse(JSON.stringify(item));
              delete t.inspectionList;
              item.inspectionList.push({
                t,
                show: false,
              });
            }

            item.undraggable = true;
            delete item.id;
          });
          processList.value = res.data.processList;
        }
        if (schemeDetail.value.compoundFlag != 1) {
          catalogues.value = catalogues.value.filter((item) => !['附件'].includes(item.name));
        }
        if (schemeDetail.value.compoundFlag == 1) {
          tabList.value = [
            {
              name: '工艺流程',
              value: 1,
            },
          ];
        }
      }
    })
    .catch((err) => {
      console.log(err);
      uni.showToast({
        mask: true,
        title: err.msg || err.message || '获取实验方案详情失败',
        icon: 'none',
      });
    });
};

const errorMsg = (list) => {
  const errMap = [];
  list.map((res) => {
    const paramListT = res.paramList;
    if (
      paramListT &&
      paramListT.length > 0 &&
      (!res.endTime || !res.startTime) &&
      res.processName != '中控'
    )
      return errMap.push(true);

    if (paramListT && paramListT.length > 0 && res.processName != '中控') {
      paramListT.map((ele) => {
        if (!ele.operateTime) return errMap.push(true);
      });
    }
  });
  return errMap;
};

const ZJReportStatusList = ref([]);

const isZJReportId = (stepList: any[]): boolean => {
  if (!stepList) return false;
  let len = stepList.length;
  const process = stepList[len - 1];
  return process.processName == '终检' &&
    ZJReportStatusList.value.length &&
    ZJReportStatusList.value.every((item) => item.status == 2)
    ? false
    : true;
};

const outListErrMsg = () => {
  const errMap = [];
  recordOutList.value.forEach((item) => {
    if (!item.invName || !item.dosage || !item.unit) return errMap.push(true);
  });

  return errMap.length > 0 ? true : false;
};

// 提交
const handleSubmit = () => {
  const params = getParams();

  const errs = errorMsg(params.stepList);
  if (errs.length > 0)
    return uni.showToast({
      mask: true,
      title: '校验不通过，工序时间填写不完全！请填完保存后，再提交审核。',
      icon: 'none',
    });

  if (!schemeDetail.value.compoundFlag) {
    if (schemeDetail.value.taskType == 10) {
      if (!ZJReportStatusList.value.length)
        return uni.showToast({
          mask: true,
          title: '终检没有报检，不允许提交。',
          icon: 'none',
        });
    }
    if (ZJReportStatusList.value.length) {
      if (isZJReportId(params.stepList))
        return uni.showToast({
          mask: true,
          title: '终检有未完成的报检，不允许提交。',
          icon: 'none',
        });
    }
  } else {
    // 复配
    if (ZJReportStatusList.value.length) {
      if (isZJReportId(params.stepList))
        return uni.showToast({
          mask: true,
          title: '终检有未完成的报检，不允许提交。',
          icon: 'none',
        });
    }
  }

  uni.showModal({
    title: '提示',
    content: '是否提交该单据',
    showCancel: true,
    success: async ({ confirm, cancel }) => {
      if (confirm) {
        uni.showLoading({
          mask: true,
        });
        // updateSave()
        const params = getParams();
        const resSave = await putObj(params);
        if (resSave.code == 0) {
          const param = {
            id: form.id,
            taskCode: schemeDetail.value.taskCode,
            compoundFlag: schemeDetail.value.compoundFlag,
          };
          submitProcess(param)
            .then((res) => {
              if (res.code == 0) {
                uni.showToast({
                  mask: true,
                  title: `单据${form.recordNo}提交成功`,
                  icon: 'none',
                });
                init({ id: form.id });
              } else {
                uni.showToast({
                  mask: true,
                  title: `单据${form.recordNo}提交失败，失败原因：${res.msg}`,
                  icon: 'none',
                });
              }
            })
            .finally(() => {
              setTimeout(() => {
                uni.hideLoading();
              }, 800);
            });
        }
      }
    },
  });
};

//撤回
const revokeShow = ref(false);
const comment = ref('');

const handleRevoke = () => {
  if (!comment.value)
    return uni.showToast({
      mask: true,
      title: `请填写撤回原因`,
      icon: 'none',
    });
  uni.showLoading({
    mask: true,
  });
  revokeProcess({
    id: form.id,
    comment: comment.value,
  })
    .then((res) => {
      if (res.code == 0) {
        uni.showToast({
          mask: true,
          title: `单据${form.recordNo}撤回成功`,
          icon: 'none',
        });
        init({ id: form.id });
        revokeShow.value = false;
        comment.value = '';
      } else {
        uni.showToast({
          mask: true,
          title: `单据${form.recordNo}撤回失败，失败原因：${res.msg}`,
          icon: 'none',
        });
      }
    })
    .finally(() => {
      uni.hideLoading();
    });
};

const completeShow = ref(false);
const completeComment = ref('');
//审核
const oncomplete = async (type: number | undefined | null) => {
  if (type && !completeComment.value) {
    return uni.showToast({
      mask: true,
      title: '请填写审核意见',
      icon: 'none',
    });
  }
  uni.showLoading({
    mask: true,
  });

  try {
    const params = {
      id: form.id,
      instanceId: form.instanceId,
      pass: type == 0 ? true : false,
      comment: completeComment.value,
    };
    await complete(params, form.id);
    uni.showToast({
      mask: true,
      title: `单据${form.recordNo}审核成功`,
      icon: 'none',
    });
    completeShow.value = false;
    completeComment.value = '';
    init({ id: form.id });
  } catch (error: any) {
    const err = error.msg || error.error || error;
    uni.showToast({
      mask: true,
      title: `单据${form.recordNo}审核失败，失败原因：${err}`,
      icon: 'none',
    });
  }

  uni.hideLoading();
};

//撤回
const reviveShow = ref(false);
const reviveComment = ref('');

const handleRevive = () => {
  if (!reviveComment.value)
    return uni.showToast({
      mask: true,
      title: `请填写弃审原因`,
      icon: 'none',
    });
  uni.showLoading({
    mask: true,
  });
  abandon({
    id: form.id,
    comment: reviveComment.value,
  })
    .then((res) => {
      if (res.code == 0) {
        uni.showToast({
          mask: true,
          title: `单据${form.recordNo}弃审成功`,
          icon: 'none',
        });
        init({ id: form.id });
        reviveShow.value = false;
        reviveComment.value = '';
      } else {
        uni.showToast({
          mask: true,
          title: `单据${form.recordNo}弃审失败，失败原因：${res.msg}`,
          icon: 'none',
        });
      }
    })
    .finally(() => {
      uni.hideLoading();
    });
};

const onAction = function (e, data) {
  switch (e.command) {
    case 'agreed':
      completeShow.value = true;
      // showApprover();
      break;
    // case 'del':
    // 	handleDelete(data);
    // 	break;
    case 'save':
      handleSaveRecord();
      break;
    // case 'close':
    //     handleClose(data);
    //     break;
    // case 'open':
    //     handleOpen(data);
    //     break;
    case 'submit':
      handleSubmit(data);
      break;
    case 'revoke':
      revokeShow.value = true;
      // handleRevoke(data);
      break;
    case 'revive':
      reviveShow.value = true;
      // handleRevive(data);
      break;
    // case 'report':
    // 	handleToForm(data);
    // 	break;
  }
};

const getProjectInfo = function (params) {
  getRdTaskDetail(params).then((res) => {
    if (res.code === 0) {
      schemeDetail.value.projectHeadName =
        res.data.rdProjectUserEntity.filter((item) => item.userType == 2) || [];
      // form.technologyHeadName = res.data.rdProjectUserEntity.filter(item => item.userType == 2) || [];
      schemeDetail.value.rdProjectUserEntity =
        res.data.rdProjectUserEntity.filter((item) => item.userType == 0) || [];
      // schemeDetail.value.projectHeadName = res.data.projectHeadName;
      // schemeDetail.value.technologyHead = res.data.technologyHead;
      // schemeDetail.value.technologyHeadName = res.data.technologyHeadName;
      // schemeDetail.value.rdProjectUserEntity = res.data.rdProjectUserEntity;
      form.taskAllStatus = res.data.taskAllStatus;
      schemeDetail.value.petitionName = res.data.petitionName;
      schemeDetail.value.taskType = res.data.taskType;
      if (schemeDetail.value.compoundFlag == 1) {
        schemeDetail.value.rdDemandEntityInvStd =
          res.data.invStd || res.data.rdDemandEntity.invStd || '';
        schemeDetail.value.rdDemandEntityInvName =
          res.data.invName || res.data.rdDemandEntity.invName || '';
      }
    }
  });
};

const removeRrocessList = [];
const onRemoveProcess = function (process) {
  if (process.id) {
    process.editProp = 'D';
    removeRrocessList.push(process);
  }
};

const getParams = function () {
  const stepList = processList.value.map((item: any, index) => {
    item.sn = index + 1;
    if (item.id) {
      item.editProp = 'M';
    } else {
      item.editProp = 'A';
    }

    item.qcFlag = item.isVerify;
    if (item.processName == '中控') {
      item.paramList = [];
      item.checkList &&
        item.checkList.map((prop) => {
          const obj = {
            mcFlag: 0,
            analysisId: prop.analysisId,
            analysisName: prop.analysisName,
            paramName: prop.itemName,
            status: prop.status,
          };
          item.paramList.push(obj);
        });

      item.sampletimeList &&
        item.sampletimeList.map((prop) => {
          const obj = {
            mcFlag: 1,
            sampleTime: prop.sampleTime,
            sampleDesc: prop.sampleDesc,
            status: prop.status,
          };
          item.paramList.push(obj);
        });
    }

    return item;
  });

  const list = JSON.parse(JSON.stringify(stepList));

  list.forEach((item) => {
    delete item.inspectionList;
    delete item.checkList;
    delete item.sampletimeList;
    return item;
  });

  recordOutList.value.forEach((item) => {
    item.type = 1;
  });
  removeRrocessList.forEach((item) => {
    if (item.processName == '中控') {
      item.paramList = [];
      item.checkList &&
        item.checkList.map((prop) => {
          const obj = {
            mcFlag: 0,
            paramName: prop.itemName,
          };
          item.paramList.push(obj);
        });

      item.sampletimeList &&
        item.sampletimeList.map((prop) => {
          const obj = {
            mcFlag: 1,
            sampleTime: prop.sampleTime,
            sampleDesc: prop.sampleDesc,
          };
          item.paramList.push(obj);
        });
    }
    delete item.checkList;
    delete item.sampletimeList;
    delete item.inspectionList;
  });

  if (schemeDetail.value.compoundFlag == 1) {
    form.attachmentName = fileList.value[0].fileName;
    form.attachment = fileList.value[0].fileUrl;
  }

  return {
    ...form,
    dosageList: [...materialList.value, ...recordOutList.value],
    stepList: [...list, ...removeRrocessList],
  };
};

const submiting = ref(false);

function queryRecordStatusBySchemeId(schemeId?: string) {
  return request({
    url: '/pm/experimentScheme/queryRecordStatusBySchemeId/' + schemeId,
    method: 'get',
  });
}

const queryRecordStatus = async (schemeId) => {
  try {
    const res = await queryRecordStatusBySchemeId(schemeId);
    if (res.code === 0) {
      return false;
    } else {
      return res.msg;
    }
  } catch (error) {
    return error.msg;
  }
};

const handleSaveRecord = async () => {
  // 从首页待办进来的
  if (_source.value == 'home' && firstView.value) {
    const res = await queryRecordStatus(schemeDetail.value.id);
    if (res) {
      showModal({
        title: '提示',
        content: `${res}\n(具体请在电脑端点击关联查询查看)`,
        cancelColor: '#333333',
        confirmColor: '#2d84fb',
        cancelText: '否',
        confirmText: '是',
        confirm: () => {
          // handleSave()
          console.log('取消');
        },
        cancel: () => {
          handleSave();
        },
      });
    } else {
      handleSave();
    }
  } else {
    handleSave();
  }
  firstView.value = false;
};

const handleSave = async function () {
  submiting.value = true;
  try {
    const params = getParams();

    if (outListErrMsg()) {
      return uni.showToast({
        mask: true,
        title: '用料产出检验不通过！有未填写的数据，请填完保存。',
        icon: 'none',
      });
    }

    // return;
    let res;
    if (form.id) {
      res = await putObj(params);
    } else {
      res = await addObj(params);
    }
    if (res.code === 0) {
      uni.showToast({
        mask: true,
        title: '保存成功',
        icon: 'none',
      });

      if (res.data) {
        init({ id: res.data });
      } else {
        init({ id: form.id });
      }
    } else {
      uni.showToast({
        mask: true,
        title: err.msg || err.message || '保存失败',
        icon: 'none',
      });
    }
  } catch (err) {
    console.log(err);
    uni.showToast({
      mask: true,
      title: err.msg || err.message || '保存失败',
      icon: 'none',
    });
  }
  submiting.value = false;
};

const updateSave = async () => {
  let res;
  const params = getParams();
  res = await putObj(params);
  console.log(res);
};

// 实验过程记录保存
const recordExp = ref();
const saveHandle = () => {
  recordExp.value.saveHandle('save');
};

const canSwitch = ref(false);
const changeTab = (val) => {
  if ([1, 2].includes(form.status) || form.taskAllStatus != 1) {
    return (tabIndex.value = val);
  }
  if (val === 0) {
    recordExp.value.saveHandle();
    tabIndex.value = val;
  } else {
    if (!form.id) {
      showModal({
        title: '提示',
        content: `当前实验记录还未生成，是否生成实验记录。`,
        cancelColor: '#333333',
        confirmColor: '#2d84fb',
        cancelText: '否',
        confirmText: '是',
        confirm: () => {
          console.log('取消');
        },
        cancel: () => {
          canSwitch.value = true;
          handleSaveRecord();
        },
      });
    } else {
      if (processList.value.some((item) => !item.id)) {
        showModal({
          title: '提示',
          content: `有新增工序未保存，是否需要保存。`,
          cancelColor: '#333333',
          confirmColor: '#2d84fb',
          cancelText: '否',
          confirmText: '是',
          confirm: () => {
            console.log('取消');
          },
          cancel: () => {
            updateSave();
            tabIndex.value = val;
          },
        });
      } else {
        updateSave();
        tabIndex.value = val;
      }
    }
  }
};

onPullDownRefresh(() => {
  init({
    id: form.id,
  });
});
</script>
<style lang="scss" scoped>
@import '../components/table';

$color-primary: #409eff;

.task-custom {
  transition: 0.32s;

  &.hide {
    top: -150rpx !important;
    color: rgb(0 0 0 / 0%);
  }
}

.scroll-container {
  display: flex;
  height: calc(100vh - 260rpx);
  transition: 0.32s;

  .viewTable {
    flex: auto;

    :deep() {
      .content {
        width: calc(100% - 100px);
      }
    }
  }

  .cell--required-icon {
    position: relative;
    display: inline-block;
    width: 0.8em;
    height: 1em;
    font-weight: 400;
    line-height: 1em;
    color: #f56c6c;

    &::before {
      position: absolute;
      top: 0.2em;
      right: 0;
      content: '*';
    }
  }

  .left-container {
    flex-shrink: 0;
    width: 240rpx;
    margin-right: 12rpx;
    overflow: hidden;
    background-color: #fff;
    transition: 0.32s;

    &.hide {
      width: 0;
      margin-right: 0;
    }

    .left {
      width: 240rpx;
    }

    .item {
      white-space: nowrap;
      border-bottom: 1rpx solid #f3f3f3;

      .item_text {
        padding: 24rpx 6rpx;
        font-size: 1rem;
        font-weight: bold;
        border-left: 6rpx solid #fff;
        transition: 0.26s;

        &.no_data {
          color: #dedede;
        }
      }

      &.active {
        .item_text {
          color: $color-primary;
          border-left: 6rpx solid $color-primary;
        }
      }
    }

    .flex-1 {
      flex: 1;
    }

    .scroll-view {
      overflow: hidden;
      transition: 0.32s;

      :deep(.form-item) {
        min-width: 520rpx;
      }

      .title {
        display: flex;
        align-items: center;
        justify-content: space-around;
        padding: 12rpx;
        margin-top: 32rpx;
        margin-bottom: 12rpx;
        font-size: 1.125rem;
        font-weight: bold;
        color: #007aff;

        text {
          margin: 0 12rpx;
        }

        .line {
          flex: 1;

          // border: 4rpx solid rgba($color: #007aff, $alpha: 0.6);
          height: 6rpx;
          margin: 0 12rpx;
          background-color: rgba($color: #007aff, $alpha: 60%);
        }
      }
    }
  }

  .craft-row-img {
    width: 80rpx;
    height: 80rpx;
  }

  .container {
    // min-height: calc(100vh - 100rpx - 24px);
    min-height: 50vh;
    background-color: #fff;
  }

  .diabledStyle {
    :deep() {
      .wd-textarea__inner {
        color: #262626 !important;
      }
    }
  }

  .viewLabel {
    position: relative;
    flex: 1;
    flex-shrink: 0;
    width: 3.75rem;
    min-width: 16.875rem;
    padding: 0.5625rem 0;
    margin: 0 0.75rem;
    font-size: 0.8125rem;
    line-height: 1;
    color: #666;
  }

  :deep() {
    .wd-textarea {
      &::after {
        display: none !important;
      }
    }
  }

  .toggle {
    position: sticky;

    // height: 80rpx;
    padding: 24rpx 12rpx 12rpx;
    overflow: hidden;

    // z-index: 2;
    // top: 0;
    color: #666;
    white-space: nowrap;
    background-color: #fff;
  }

  .open {
    position: fixed;
    z-index: -1;
    width: 40rpx;
    padding: 32rpx 0;
    line-height: 1;
    color: #fff;
    text-align: center;
    background-color: rgba($color: #000, $alpha: 50%);
    border-top-right-radius: 12rpx;
    border-bottom-right-radius: 12rpx;
    opacity: 0;
    transition: 0.26s;

    &.show {
      z-index: 999;
      opacity: 1;
    }
  }

  .chart-container {
    padding-top: 24rpx;
  }
}

:deep() {
  .wdPopupStyle {
    width: 50vw;
    border-radius: 20rpx;

    .title {
      padding: 20rpx 0;
      font-size: 40rpx;
      text-align: center;
    }

    .content-body {
      padding: 40rpx;
    }

    .flow-btn-fixed {
      width: 100%;
      background-color: white;
      border-top: 1px solid #f2f2f1;
    }

    .btn_group {
      display: flex;
      justify-content: space-between;

      // margin: 0rpx 0 20rpx;
      border-bottom: 1px solid #f2f2f1;

      .btn {
        display: flex;

        // width: 49%;
        flex: 1;
        align-items: center;
        justify-content: center;
        height: 40px;
        font-size: 32rpx;
        color: black;
        background-color: white !important;
        border-left: 1px solid #f7f7f7;
        border-radius: 0 !important;

        // color: white;
        border-radius: 6rpx;
      }

      .danger {
        color: #f56c6c;
      }

      .primary {
        color: $color-primary;
      }
    }
  }
}

.tabs-wrap {
  padding: 12rpx 24rpx 24rpx;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .tabs {
      position: relative;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      padding-left: 24rpx;

      &::after {
        position: absolute;
        top: 4rpx;
        bottom: 4rpx;
        left: 0;
        width: 8rpx;
        content: '';
        background-color: #2e5cf6;
        border-radius: 3rpx;
      }

      .tab {
        margin-right: 12px;

        &.on text {
          color: #2e5cf6;
        }
      }

      text {
        font-size: 1.0625rem;
        font-weight: bold;
        color: #000;
      }
    }
  }
}
</style>
